/**
 * BrandBigData.com Inc.
 * Copyright (c) 2016 All Rights Reserved.
 */
package com.qibao.toolkit.dbqueue;

import java.util.Collection;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author xumin
 * @version $Id:DbQueueDAO.java, v0.1 2018/03/29 18:31 xumin
 */
@Repository
@Transactional
public interface DbQueueMessageDAO extends JpaRepository<DbQueueMessageDO, Integer> {

    @Query(value = "SELECT  d FROM  DbQueueMessageDO  d where d.status=2 AND  d.topic = ?1 AND d.locker = ?2 ")
    List<DbQueueMessageDO> selectLockedMessage(String topic, String locker);


    List<DbQueueMessageDO> findByStatusAndTopic(int status,String topic,Pageable pageable);
    @Modifying
    @Query("update DbQueueMessageDO t set t.status=2,t.locker=?2 where t.status=1 and t.topic=?1 and t.id in(?3)")
    int lockTasks(String topic,String locker,Collection<Integer> tryLockIds);
   /* @Query(value = "UPDATE DbQueueMessageDO d SET d.status=2,d.locker=?2 WHERE d.status=1 AND d.topic=?1 ")
    @Modifying
    int lockTask(String topic, String locker);*/

    @Query("UPDATE DbQueueMessageDO t SET t.status=1 WHERE t.status=2 AND SUBTIME(gmtModified,'01:00:00')<now()")
    int unlockTasks();

    @Query("UPDATE DbQueueMessageDO t SET t.status=?2,t.errorMsg=?3 WHERE id=?1")
    @Modifying
    int updateStatus(int id, int status, String errorMsg);

    @Query("SELECT t from DbQueueMessageDO t where t.status=1 and t.topic=?1")
    List<DbQueueMessageDO> getRecord(Pageable pageable);
}
